package com.huluobo.a2204kotlinjetpackdemo.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.Flow

/**
 *  Created by LC on 2024/8/19.
 */
class PagingViewModel : ViewModel() {
    fun getPagingData(): Flow<PagingData<GitPagingBean>> {
        return Repo.getPagingData().cachedIn(viewModelScope)
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val apiService = PagingApiService.create()

    //prefetchDistance表示距离剩余多少条数据开始预加载
    //设置0表示滑动到底部才进行加载,默认值是当前分页的大小,当前是pageSize的5倍,也就是剩余不足25条就进行加载
    //pagingSourceFactory 数据加载的工厂,直接放之前写的数据源即可
    //flow 让数据源形成一个flow流,可以给页面进行数据发送
    fun getPagingData(): Flow<PagingData<GitPagingBean>> {
        return Pager(
            PagingConfig(PAGE_SIZE, PAGE_SIZE * 5),
            null,
            { RepoPagingSource(apiService) }
        ).flow
    }
}